<template>
    <div>
        <div class="header">
            <div class="">
                <el-button @click="start" :icon="Search" size="default" type="primary">
                    查询
                </el-button>
                <router-link custom :to="{ name: chgMyQuestionBankRouteName, params: { ID: 0 } }" v-slot="{ navigate }">
                    <el-button @click="navigate" size="default" type="primary">
                        + 创建我的专题
                    </el-button>
                </router-link>
            </div>
        </div>
        <div class="">
            <div class="">
                <!-- @selection-change="handleChange" :highlight-current-row="!!userhandleCurrentChange"
                @current-change="userCurrentChange"
                @cell-click="userhandleCurrentChange ? userhandleCurrentChange : () => { }" -->
                <el-table :data="tableData" border height="73vh" style="width: 100%" @sort-change="sortchange">
                    <template v-slot:empty>
                        <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
                    </template>
                    <el-table-column label="ID" prop="ID" sortable></el-table-column>
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="题目数" prop="questionquestionbankcount">
                        <template #default="{ row }">
                            {{ row?.questionquestionbank?.length }}
                        </template>
                    </el-table-column>
                    <el-table-column label="答题记录" prop="userquestioncount"></el-table-column>
                    <el-table-column label="标签" prop="label"></el-table-column>
                    <el-table-column label="创建时间" prop="createdAt" sortable
                        :formatter="({ createdAt }) => formatDate({ updatedAt: createdAt })">
                    </el-table-column>
                    <el-table-column label="操作" width="300">
                        <template #default="{ row }">
                            <router-link custom :to="{ name: chgMyQuestionBankRouteName, params: { ID: row.ID } }"
                                v-slot="{ navigate }">
                                <el-button size="default" @click.stop="navigate">编辑</el-button>
                            </router-link>
                            <el-button size="default" @click.stop="del(row.ID)" type="danger">删除</el-button>
                            <el-button plain type="">
                                <a target="_blank"
                                    :href="`${pdfBaseUrl}/question.html?questionbankid=${row.ID}&title=${row.name}`"
                                    type="primary">保存专题为pdf</a>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <el-pagination class="pager" @current-change="handleCurrentChange" :page-size="Number(limit)"
            layout="total, prev, pager, next" :total="totalCount">
        </el-pagination>
    </div>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import { Iobj, asyncdelquestionbank, asyncgetmyquestionbank } from "../../../api/index";
import { Storekey } from "../../../interface";
import { default as Studycodemodel, default as study } from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";

const pdfBaseUrl = process.env.NODE_ENV === 'production' ? 'https://oj.hterobot.com' : '';
const chgMyQuestionBankRouteName = "修改我的专题"

const store = useStore(Storekey)
const user = computed<Studycodemodel.Iuser>(() => {
    return store.getters.getuser;
});
const teamId = computed(() => {
    return Number(user.value?.teamid)
})

const sortable = ref('DESC')
const limit = ref(20)
const offset = ref(0)
const order = ref('ID')
const like = ref()
const dialogVisibleUpdateSort = ref(false)

const questionbanks = ref<study.Iquestionbank[]>([])
const _questionbanks = ref<study.Iquestionbank[]>([])

const tableData = ref<study.Iquestionbank[]>([])
const totalCount = ref(0)

async function start() {
    try {
        let _like: [keyof study.Iquestionbank, string | number] | undefined;

        if (like.value) {
            _like = ["name", like.value];
        }
        const query: Iobj<study.Iquestionbank> = {
            _limit: limit.value,
            _offset: offset.value,
            _order: order.value,
            _sortable: sortable.value,
            _like,
        }
        const { rows, count } = await asyncgetmyquestionbank(query);
        tableData.value = rows
        totalCount.value = count
    } catch (e: any) {
        ElMessage.error(e);
    }
}

onMounted(() => {
    start()
})

function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
    start()
}

// 
function sortchange(row: { prop: any; order: any }) {
    const { prop, order } = row;
    console.log(prop, order, order == "descending")
    if (order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    if (prop) {
        order.value = prop;
    }
}
function formatDate({ updatedAt }: any) {
    return toLocaleDateString(updatedAt);
}
// function handleChange(data: study.Iquestionbank[]) {
//     if (p.handleSelectionChange) p.handleSelectionChange(data);
// }
// function userCurrentChange(data: study.Iquestionbank) {
//     if (p.userhandleCurrentChange) p.userhandleCurrentChange(data);
// }

async function del(ID?: number) {
    if (ID) {
        ElMessageBox.confirm("你确定要删除此题吗", "提示").then(async () => {
            try {
                await asyncdelquestionbank({ ID });
                ElMessage.success("删除成功");
                start();
            } catch (e: any) {
                ElMessage.error(e);
            }
        });
    }
}

</script>

<style scoped>
.header {
    margin-bottom: 20px;
}

.pager {
    margin-top: 20px;
    float: right;
}
</style>